<?php
namespace App\DBs;

use App\DBs\BaseDB;
use Illuminate\Support\Facades\DB;

class AppVersionDB extends BaseDB
{
    /**
     * BUG
     * version 版本号
     * link 下载地址
     * total 下载量
     */

    protected $table = 'app_version';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 列表
     */
    public function getIndex()
    {
        $models = DB::table($this->table)
            ->orderBy('version','desc')
            ->get();
        if (!count($models)) {
            return array('code'=>1, 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            $dataArr[] = [
                'id' => $model['id'],
                'version' => $model['version'],
                'total' => $model['total'],
                'link' => $model['link'],
            ];
        }
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 详情
     */
    public function getNewOne($version)
    {
        $models = DB::table($this->table)
            ->where('version','>',$version)
            ->orderBy('version','desc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $model = $this->jsonToArr($models[0]);
        $dataArr = array(
            'id' => $model['id'],
            'version' => $model['version'],
            'total' => $model['total'],
            'link' => $model['link'],
        );
        return array('code'=>'0', 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 下载量
     */
    public function setDownloadTotal($id, $totalOld)
    {
        $totalNew = $totalOld + 1;
        //更新下载量
        DB::table($this->table)->where('id',$id)
            ->update(['total'=> $totalNew]);
        $dataArr = array(
            'total' => $totalNew,
        );
        return array('code'=>'0', 'msg'=>'操作成功', 'data'=>$dataArr);
    }

//    /**
//     * 新增
//     */
//    public function setAdd($admin,$alm,$genre,$name,$link,$detail)
//    {
//        //开启事务
//        DB::beginTransaction();
//        try {
//            $lastId = DB::table($this->table)->insertGetId([
//                'name' => $name,
//                'link' => $link,
//                'detail' => $detail,
//                'admin' => $admin,
//                'alm' => $alm,
//                'genre' => $genre,
//                'created_at' => time(),
//            ]);
//            $dataArr = array(
//                'proId' => $lastId,
//            );
//            //提交事务
//            DB::commit();
//            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
//        } catch (\Exception $e) {
//            //事务回滚
//            DB::rollBack();
//            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
//        }
//    }
}